package com.xtm.exercise.service.impl;

import com.xtm.exercise.service.LogisticsOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.Executor;

/***
 *@Author: 王磊
 *@CreateTime: 2025-06-11  19:47
 *@Description: TODO
 *@title: LogisticsOrderServiceImpl
 */
@Service
@Slf4j
public class LogisticsOrderServiceImpl implements LogisticsOrderService {

    @Resource
    private TaskExecutor taskExecutor;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOperateHistory() {

        log.info("1、提交事务之前，生成操作记录");

        // 提交事务之后执行
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCompletion(int status) {
                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                    taskExecutor.execute(()-> addBusinessHisotry());
                }
            }
        });

        log.info("2、提交事务之后，生成操作记录");

    }

    private void addBusinessHisotry(){
       log.info("3、提交事务之后执行，执行业务操作");
    };
}
